public class DistributorSendShipment{

    String UrlId = System.currentPageReference().getParameters().get('id');
    List<PESampleRequest__c> target = [select id,Barcode__c, ApprovalStatus__c from PESampleRequest__c where Id =: System.currentPageReference().getParameters().get('id')];
    public List<PESampleRequestItem__c> PESampleRecords {
        get;      
        set;
    }
    
   public DistributorSendShipment()
   {
       PESampleRecords = [Select id,SalesCity__c,SendUnit__c,Unit__c,Product__c, ProductName__c From PESampleRequestItem__c Where PESampleRequest__c =: System.currentPageReference().getParameters().get('id')];
   } 
    
    
    public PESampleRequest__c PESample{
        get{
            if (PESample==null)
                if(target.size() > 0){
                    PESample = target[0];
                }
                else
                    PESample = null;
            return PESample;
        }
        set;
    }
    
    
    public PageReference Save() {
        if(PESample.ApprovalStatus__c == '审批通过'){
            PESample.SendShipment__c = true;
            update PESample;
        }
        if(PESampleRecords.size() >0 )
        {
            Update PESampleRecords;
        }

        List<Delivery__c> DeliveryList = new List<Delivery__c>();
        
        
        List<ShipmentCity__c> CityList = Database.query('Select id,ShipmentCity__c From ShipmentCity__c Where '+' SalesCity__c includes(\''+ PESampleRecords[0].SalesCity__c + '\')');
        
        for(PESampleRequestItem__c pe : PESampleRecords)
        {
            if(CityList.size() > 0){
                List<CityInventory__c> CIList = [Select id  From CityInventory__c Where ShipmentCity__r.ShipmentCity__c =: CityList[0].ShipmentCity__c and Product__c =: pe.Product__c];
                if(CIList.size() > 0){
                    Delivery__c del = new Delivery__c();
                    del.Product__c = pe.Product__c;
                    del.Unit__c = pe.SendUnit__c;
                    del.Type__c = 'PE Request';
                    del.CityInventory__c = CIList[0].id;
                    DeliveryList.add(del);
                }
            }
        }
        if(DeliveryList.size() > 0)
            insert DeliveryList;

        return new ApexPages.StandardController(new PESampleRequest__c(Id = UrlId)).view();    
    }

    public PageReference Cancel() {
        return new ApexPages.StandardController(new PESampleRequest__c(Id = UrlId)).view();
    }
    
    static testMethod void DistributorSendShipmentTest()
    {
        PESampleRequest__c PESample = new PESampleRequest__c(Name = 'a', DateShipped__c = date.today() + 10, ApprovalStatus__c = '审批通过');
        insert PESample;
        
        DistributorSendShipment testcase = new DistributorSendShipment();
        testcase.target.add(PESample); 
        testcase.Save();
        testcase.Cancel();
        
    }
}